<template>
  <div class="slideshow-container">
    <a-carousel v-if="!loading" :autoplay="true" :dots="false" ref="carousel" class="custom-carousel">
      <div v-for="(image, index) in images" :key="index" class="carousel-slide">
        <img :src="image.src" :alt="image.alt" class="carousel-image">
      </div>
    </a-carousel>

    <div v-else class="loading-container">
      <div class="loader"></div>
    </div>

    <button class="prev" @click="prevSlide">&#10094;</button>
    <button class="next" @click="nextSlide">&#10095;</button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { baseURL, getHomecarouselAPI } from '../apis/homeAPI.js';

const loading = ref<boolean>(true);
const images = ref([]);

const getHomecarousel = async () => {
  try {
    const res = await getHomecarouselAPI();
    const { data } = res;
    images.value = data.map(item => ({
      alt: item.attributes.alt,
      src: baseURL + `${item.attributes.src.data.attributes.url}`,
    }));
  } catch (error) {
    console.error('Error fetching data:', error);
  } finally {
    loading.value = false;
  }
};

const carousel = ref(null);

const nextSlide = () => {
  carousel.value.next();
};

const prevSlide = () => {
  carousel.value.prev();
};

onMounted(() => {
  getHomecarousel();
});
</script>

<style scoped>
.slideshow-container {
  position: relative;
  max-width: 1500px;
  height: 500px;
  margin: 20px auto;
  overflow: hidden;
}

.custom-carousel {
  height: 100%;
}

.carousel-slide {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  background: #364d79;
  overflow: hidden;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
}

.prev,
.next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  font-size: 24px;
  padding: 15px;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
  z-index: 1;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.prev {
  left: 10px;
}

.next {
  right: 10px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px; /* 设置高度以使加载图标居中 */
}

.loader {
  border: 8px solid rgba(255, 255, 255, 0.3); /* 背景透明的边框 */
  border-top: 8px solid #3498db; /* 顶部颜色 */
  border-radius: 50%; /* 圆形 */
  width: 50px; /* 图标宽度 */
  height: 50px; /* 图标高度 */
  animation: spin 1s linear infinite; /* 旋转动画 */
}

/* 定义旋转动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
